import { Context, Next } from 'koa'
// import logger from 'koa-logger';
import chalk from 'chalk'
import dayjs from 'dayjs'

export const loggerMiddleware = async (ctx: Context, next: Next) => {
    const start = Date.now()
    await next()

    // 记录响应时间
    const ms = Date.now() - start
    const logInfo = {
        time: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
        method: ctx.method,
        url: ctx.url,
        body: ctx.request.body,
        status: ctx.status,
        timeUsed: `${ms}ms`,
        ip: ctx.ip
    }

    // 根据状态码区分日志级别
    if (ctx.status >= 500) {
        console.error(chalk.red('日志：' + JSON.stringify(logInfo)))
    } else if (ctx.status >= 400) {
        console.warn(chalk.yellow('日志：' + JSON.stringify(logInfo)))
    } else {
        console.info(chalk.green('日志：' + JSON.stringify(logInfo)))
    }
}
